﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Navigation;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input.Touch;
using System.Collections.Generic;

namespace SheepClock
{
    public partial class MainPage : PhoneApplicationPage
    {
        GameTimer timer;
        SpriteBatch spriteBatch;
        UIElementRenderer uiRenderer;

        string timeFormat = "HH:mm";
        Microsoft.Xna.Framework.Color tintColor = Microsoft.Xna.Framework.Color.White;
        System.Windows.Media.SolidColorBrush myThemeBrush;
        System.Windows.Media.SolidColorBrush myBackgoundBrush;

        bool runningSheep;
        bool sheepBaa;

        Texture2D fence;
        Sheep mainSheep;
        public static SoundEffect sheepSound;

        int tempFps = 0;
        int fps = 0;

        //herd mode
        int hits = 0;
        DispatcherTimer herdTimer;
        List<Sheep> herd;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            GlobalParams.contentManager = (Application.Current as App).Content;


            UpdateSettingsVeriables();


            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(300000);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            herdTimer = new DispatcherTimer();
            herdTimer.Interval = new TimeSpan(0, 0, 2);
            herdTimer.Tick += new EventHandler(herdTimer_Tick);

            herd = new List<Sheep>();

            fence = GlobalParams.contentManager.Load<Texture2D>("fence_white");
            mainSheep = new Sheep(15);
            sheepSound = GlobalParams.contentManager.Load<SoundEffect>("baa");

            myThemeBrush = Application.Current.Resources["PhoneAccentBrush"] as System.Windows.Media.SolidColorBrush;
            myBackgoundBrush = Application.Current.Resources["PhoneBackgroundBrush"] as System.Windows.Media.SolidColorBrush;
            tintColor = Microsoft.Xna.Framework.Color.FromNonPremultiplied(myThemeBrush.Color.R, myThemeBrush.Color.G, myThemeBrush.Color.B, myThemeBrush.Color.A);

            DispatcherTimer fpsTimer = new DispatcherTimer();
            fpsTimer.Interval = new TimeSpan(0, 0, 1);
            fpsTimer.Tick += new EventHandler(fpsTimer_Tick);
            fpsTimer.Start();


            colorsList.Items.Add(new ColorListItem("My theme", "Images/wpLogo.png"));
            colorsList.Items.Add(new ColorListItem("Night blue", System.Windows.Media.Color.FromArgb(255, 0, 227, 232)));
            colorsList.Items.Add(new ColorListItem("Cherry red", System.Windows.Media.Color.FromArgb(255, 255, 0, 0)));
            colorsList.Items.Add(new ColorListItem("Grass green", System.Windows.Media.Color.FromArgb(255, 0, 255, 0)));
            colorsList.Items.Add(new ColorListItem("Lavender purple", System.Windows.Media.Color.FromArgb(255, 156, 0, 224)));
            colorsList.Items.Add(new ColorListItem("Sunset orange", System.Windows.Media.Color.FromArgb(255, 244, 90, 15)));
            //colorsList.Items.Add(new ColorListItem("Nokia blue", System.Windows.Media.Color.FromArgb(255, 0, 129, 222)));


            int previousIndex = IsolatedStorageSettings.ApplicationSettings.Contains("ColorIndex") ?
                (int)IsolatedStorageSettings.ApplicationSettings["ColorIndex"] : 0;
            colorsList.SelectedIndex = previousIndex;
            colorsList_SelectionChanged(colorsList, null);

            colorsList.MinHeight = colorsList.Items.Count * 49;
            (colorsList.Items[colorsList.SelectedIndex] as ColorListItem).Selected = true;
            colorsList.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(colorsList_SelectionChanged);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            timer.Start();

            PopImageBack(colorButton);
            PopImageBack(alarmsButton);
            PopImageBack(settingsButton);

            UpdateSettingsVeriables();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            timer.Stop();

            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        private void UpdateSettingsVeriables()
        {
            runningSheep = IsolatedStorageSettings.ApplicationSettings.Contains("SheepRunning") ?
                (bool)IsolatedStorageSettings.ApplicationSettings["SheepRunning"] : true;
            sheepBaa = IsolatedStorageSettings.ApplicationSettings.Contains("SheepBaa") ?
                 (bool)IsolatedStorageSettings.ApplicationSettings["SheepBaa"] : true;
        }

        void colorsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            for (int i = 0; i < colorsList.Items.Count; i++)
            {
                if (i == colorsList.SelectedIndex)
                {
                    (colorsList.Items[i] as ColorListItem).Selected = true;
                    IsolatedStorageSettings.ApplicationSettings["ColorIndex"] = i;
                }
                else
                    (colorsList.Items[i] as ColorListItem).Selected = false;
            }

            System.Windows.Media.Brush itemBrush = (colorsList.SelectedItem as ColorListItem).ColorRectangle.Fill;
            if (itemBrush is System.Windows.Media.SolidColorBrush)
            {
                System.Windows.Media.SolidColorBrush brush = itemBrush as System.Windows.Media.SolidColorBrush;
                tintColor = Microsoft.Xna.Framework.Color.FromNonPremultiplied(brush.Color.R, brush.Color.G, brush.Color.B, brush.Color.A);
            }
            else
            {
                tintColor = Microsoft.Xna.Framework.Color.FromNonPremultiplied(myThemeBrush.Color.R, myThemeBrush.Color.G, myThemeBrush.Color.B, myThemeBrush.Color.A);
            }

            colorsList.Visibility = Visibility.Collapsed;
            PopImageBack(colorButton);
        }

        private void HideColorsList()
        {
            if (colorsList.Visibility == Visibility.Visible)
            {
                colorsList.Visibility = Visibility.Collapsed;
                PopImageBack(colorButton);
            }
        }

        void fpsTimer_Tick(object sender, EventArgs e)
        {
            fps = tempFps;
            tempFps = 0;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        void herdTimer_Tick(object sender, EventArgs e)
        {
            herdTimer.Stop();

            if (hits >= 3)
            {
                herd.Clear();
                Random r=new Random(DateTime.Now.Second);
                for (int i = 0; i < 10; i++)
                {
                    float velocity=(float)(15+r.NextDouble()*25);
                    Sheep herdSheep = new Sheep(velocity);
                    herdSheep.BelongsToHerd = true;
                    int delay=(int)(100+r.NextDouble()*200);
                    herdSheep.SetDelayThroughXPosition(delay);
                    herd.Add(herdSheep);
                }
            }

            hits = 0;
        }

        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            timeText.Text = DateTime.Now.ToString(timeFormat);
            dateText.Text = DateTime.Now.ToLongDateString();
            fpsText.Text = fps.ToString();

            mainSheep.Update();

            for (int i = herd.Count - 1; i >= 0; i--)
            {
                if (herd[i].IsOutOfTheScreen)
                    herd.RemoveAt(i);
                else
                    herd[i].Update();
            }

            if (sheepBaa)
            {
                TouchCollection touches = TouchPanel.GetState();
                if (touches.Count > 0)
                {
                    TouchLocation touch = touches[0];
                    if (touch.State == TouchLocationState.Pressed && mainSheep.ContainsTouch(touch))
                    {
                        if (!herdTimer.IsEnabled)
                            herdTimer.Start();
                        hits++;
                        sheepSound.Play();
                    }
                }
            }
        }

        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            tempFps++;

            timeText.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromArgb(tintColor.A, tintColor.R, tintColor.G, tintColor.B));
            dateText.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromArgb(tintColor.A, tintColor.R, tintColor.G, tintColor.B));
            uiRenderer.Render();

            //SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.Black);
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(new Microsoft.Xna.Framework.Color(myBackgoundBrush.Color.R, myBackgoundBrush.Color.G, myBackgoundBrush.Color.B));

            spriteBatch.Begin();

            if (runningSheep)
            {
                Rectangle fenceRectangle = new Rectangle(
                    ((int)ActualWidth - fence.Width) / 2,
                    (int)ActualHeight - fence.Height,
                    fence.Width, fence.Height);
                spriteBatch.Draw(fence, fenceRectangle, tintColor);

                mainSheep.Draw(spriteBatch, tintColor);

                foreach (Sheep sheep in herd)
                {
                    sheep.Draw(spriteBatch, tintColor);
                }
            }

            spriteBatch.Draw(uiRenderer.Texture, Vector2.Zero, Microsoft.Xna.Framework.Color.White);
            spriteBatch.End();
        }

        private void PhoneApplicationPage_LayoutUpdated(object sender, EventArgs e)
        {
            int width = (int)ActualWidth;
            int height = (int)ActualHeight;
            GlobalParams.ScreenWidth = width;
            GlobalParams.ScreenHeight = height;

            if (width <= 0 || height <= 0)
                return;

            if (uiRenderer != null &&
                uiRenderer.Texture != null &&
                uiRenderer.Texture.Width == width &&
                uiRenderer.Texture.Height == height)
            {
                return;
            }

            if (uiRenderer != null)
                uiRenderer.Dispose();

            uiRenderer = new UIElementRenderer(this, width, height);
        }

        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            if (Orientation == PageOrientation.Portrait || Orientation == PageOrientation.PortraitUp || Orientation == PageOrientation.PortraitDown)
                timeFormat = "HH:mm";
            else if (Orientation == PageOrientation.Landscape || Orientation == PageOrientation.LandscapeLeft || Orientation == PageOrientation.LandscapeRight)
                timeFormat = "HH:mm:ss";
        }


    }

}